import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/device_list_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 切换设备 页面
class DeviceListPage extends ConsumerStatefulWidget {
  const DeviceListPage({super.key});

  @override
  ConsumerState<DeviceListPage> createState() => _DeviceListPageState();
}

class _DeviceListPageState extends ConsumerState<DeviceListPage> {
  bool showLoading = true;
  int pageNum = 1;
  List<DeviceListData> deviceList = <DeviceListData>[];
  late EasyRefreshController _refreshController;

  _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _buildList() {
    return ListView.builder(
      itemCount: deviceList.length,
      itemBuilder: (context, index) {
        return _buildCell(index);
      },
    );
  }

  _buildCell(int index) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    DeviceListData device = deviceList[index];
    bool isCurrentDevice = deviceInfo.imei == device.imei;
    // 设备信息cell
    return GestureDetector(
      onTap: () async {
        // 跳转到设备信息页面
        if (isCurrentDevice) {
          context.pop();
        } else {
          ref.read(deviceInfoProvider.notifier).switchImei(device.imei!, () {
            context.pop();
          });
        }
      },
      child: Stack(
        children: [
          Container(
            height: 60,
            margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
            ),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  AppTheme.themeConfig.greyBgColor,
                ],
              ),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.06),
                  blurRadius: 8,
                  offset: const Offset(0, 3),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // 设备名称和设备码
                      Text(
                        '${device.deviceName}',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.themeConfig.primaryTextColor,
                          letterSpacing: 0.2,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(
                        height: 4,
                      ),
                      Text(
                        '设备号：${device.imei ?? ''}',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: AppTheme.themeConfig.secondaryTextColor,
                        ),
                      ),
                    ],
                  ),
                ),
                // 设备状态
                _buildDeviceStatus(device.deviceStatus ?? 0),
              ],
            ),
          ),
          // 右上角显示当前设备标签
          if (isCurrentDevice)
            Positioned(
              top: 20,
              right: 20,
              child: Container(
                // height: 20,
                alignment: Alignment.center,
                padding: const EdgeInsets.only(
                  left: 4,
                  right: 4,
                ),
                decoration: BoxDecoration(
                    color: AppTheme.themeConfig.primaryColor,
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(8),
                      bottomLeft: Radius.circular(8),
                    )),
                child: const Icon(Icons.check, color: Colors.white, size: 16),
              ),
            )
        ],
      ),
    );
  }

  Widget _buildDeviceStatus(int deviceStatus) {
    switch (deviceStatus) {
      case 2:
        return _buildDeviceStatusView('离线', '#909399');
      case 1:
        return _buildDeviceStatusView('在线', '#19be6b');
      case 3:
        return _buildDeviceStatusView('睡眠', '#ff9900');
      case 4:
        return _buildDeviceStatusView('关机', '#fa3534');
      default:
        return _buildDeviceStatusView('未激活', '#c8c9cc');
    }
  }

  Widget _buildDeviceStatusView(String text, String color) {
    return Container(
      margin: const EdgeInsets.only(left: 10),
      padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
      decoration: BoxDecoration(
        color: ColorUtils.hexToColor(color),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: ColorUtils.hexToColor(color).withOpacity(0.3),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600,
          letterSpacing: 0.3,
        ),
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build完成后回调
      // 获取设备列表
      _fetchDeviceList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchDeviceList(bool isRefresh) async {
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 10,
    };
    final res = await get<DeviceListResp, DeviceListResp>('/device/list',
        queryParameters: queryParams, decodeType: DeviceListResp());
    res.when(success: (DeviceListResp resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          deviceList.clear();
          deviceList.addAll(resp.data!);
          // 判断是否还有更多数据
          if (resp.data == null || resp.data!.isEmpty || resp.data!.length < 10) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            _refreshController.finishRefresh();
          }
          pageNum++;
        } else {
          if (resp.data == null || resp.data!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            pageNum++;
            deviceList.addAll(resp.data!);
            _refreshController.finishLoad();
          }
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '设备列表',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: EasyRefresh(
        controller: _refreshController,
        onRefresh: () async {
          pageNum = 1;
          await _fetchDeviceList(true);
          _refreshController.finishRefresh();
        },
        onLoad: () async {
          await _fetchDeviceList(false);
        },
        child: showLoading ? _buildLoading() : _buildList(),
      ),
    );
  }
}
